from django.http import HttpResponse
from django.shortcuts import render_to_response

from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
from django.contrib import auth
from scriptt import DATAITEM

import sys
import scriptt
import copy
import cjson
import urllib

def urldecode(query):
    d = {}
    a = query.split('&')
    for s in a:
        if s.find('='):
            k,v = map(urllib.unquote, s.split('='))
            try:
                d[k].append(v)
            except KeyError:
                d[k] = [v]
    return d


def test1(request):     
    a = A()
    a.i += 1
    return HttpResponse("hello" + str(a.i))

def test2(request):
	weather=WSDL.Proxy('http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl')
	weather.soapproxy.config.buildWithNamespacePrefix = 0
	for i in weather.methods:
		weather.methods[i].namespace = weather.wsdl.targetNamespace
	result=weather.getWeatherbyCityName(theCityName='54830')
	
	return HttpResponse(result)


def test3(request):
    c=scriptt.ScriptEngine(stockid='600001')
    print c.stockid
    return HttpResponse(str(c.names))

class Indice:

    def __init__(self, value, name):
        self.name = name
        self.value = value

    def __str__(self):
        return "(" + str(self.name) + "->" + str(self.value) + ")";

    def __repr__(self):
        return "(" + str(self.name) + "->" + str(self.value) + ")";

class IndiceSeq:

    def __init__(self, seq, date):
        self.seq = seq
        self.date = date

    def __str__(self):
        return "(" + str(self.seq) + "," + str(self.date) + ")";

    def __repr__(self):
        return "(" + str(self.seq) + "," + str(self.date) + ")";    
    
@csrf_exempt
def test4(request):
    if request.method == 'POST':
        #url = request.get_full_path()
        stockid = request.POST['stockid']
        
        sdate = request.POST.get('sdate', '19900101')
        edate = request.POST.get('edate', '20991231')

        print stockid, sdate, edate
        s = request.POST['script']
        s = urllib.unquote(s)
        s = s.split('\n')
        print s
        
        #stockidarr = cjson.decode(stockid)
        #for stockid in stockidarr:

        #import cx_Oracle
        
        #connection = cx_Oracle.connect('istock_user', 'istock_user', 'localhost:1521/istock')
        cursor = connection.cursor()
        sql = "select OPEN, HIGH, LOW, CLOSE, VOLUMN, ADJCLOSE, DATETIME from STOCK_DAYLINE_INFO where STOCK_ID='"+str(stockid)+"'" + " and DATETIME>='"+str(sdate)+"' and DATETIME <= '" +str(edate)+"' order by DATETIME"
        
        cursor.execute(sql)        
        rows = cursor.fetchall()

        openlist = []
        highlist = []
        lowlist = []
        closelist = []
        volumn = []
        adjclose = []
        
        for i in range(0, len(rows)):
                date = int(rows[i][6])
                openlist.append(DATAITEM(float(rows[i][0]), date))
                highlist.append(DATAITEM(float(rows[i][1]), date))
                lowlist.append(DATAITEM(float(rows[i][2]), date))
                closelist.append(DATAITEM(float(rows[i][3]), date))
                volumn.append(DATAITEM(float(rows[i][4]), date))
                adjclose.append(DATAITEM(float(rows[i][5]), date))
            
        c=scriptt.ScriptEngine(stockid=stockid, startdate=str(sdate), enddate=str(edate),
                               openlist = openlist, highlist=highlist, lowlist=lowlist,
                               closelist= closelist, volumn=volumn, adjclose=adjclose)
        
        for i in s:
            print i
            c.parse(i)

        print c.names
            #print c.__dict__
        
        num = []
        vector = []
        num_names = []
        vector_names = []
        
        for k in c.names.keys():
            
            indice = copy.deepcopy(c.names[k])
            #print dir(indice)
            if indice.isvector == 0:
                num.append(indice)
                num_names.append(k)
            else:
                vector_names.append(k)
                vector.append((indice, k))
        
        currd = []
        merge = []
        
        for i in range(0, len(vector)):
            currd.append(0)

        done = 0
        #print dir(vector[0].data)
        while not done:
            mind = 30000101
            mini = -1
            flag = 0
            li = []
            for i in range(0, len(vector)):
                if currd[i] >= len(vector[i][0].data):
                    continue
                flag = 1
                if int(vector[i][0].data[currd[i]].date) < mind:
                    mind = int(vector[i][0].data[currd[i]].date)
                    mini = i

            if not flag:
                done = 1
                break

            print mind, mini
            
            li.append(Indice(vector[mini][0].data[currd[mini]].value, vector[mini][1]))
            currd[mini] += 1
            
            for i in range(0, len(vector)):
                if currd[i] >= len(vector[i][0].data):
                    continue
                if int(vector[i][0].data[currd[i]].date) == mind:
                    if i == mini:
                        continue
                    li.append(Indice(vector[i][0].data[currd[i]].value, vector[i][1]))
                    currd[i] += 1

            print str(li) + "$$"            
            merge.append(IndiceSeq(li, mind))

        print str(merge) +"&*"
        
        for i in merge:
            if len(i.seq) == len(vector_names):
                continue
            tm = []
            for j in i.seq:
                tm.append(j.name)
            for j in vector_names:
                if j not in tm:
                    i.seq.append(Indice(None, j))
                    i.seq.sort(cmp=lambda x,y:cmp(x.name, y.name))
                    
        print str(currd) + "##"
        print str(merge) +"&*"

        nlist = vector_names
        nlist.sort()
        #print li
        #for i in li:                        
        #    print i

        #mind = i[0].data[0].date
        #maxd = i[0].data[-1].date
        #{'indices':li}
        #for i in range(1, len(li)):
                                                
        #
        return render_to_response('stock_detail.html', {'indices':merge, 'vectornames':nlist, 'numnames':num_names, 'num':num})
        #return HttpResponse(str(c.names))


def test5(request):
    c = {}
    c.update(csrf(request))
    
    return render_to_response('stest.html', c)

def test6(request):
    
    return render_to_response('stock_show.html')

def test7(request):
    return render_to_response('stock_formula.html')

def test8(request):
    if request.method == 'POST':
        try:
            sid = request.POST['sid']
            sds = request.POST['sds']
            script = request.POST['script']
            import datetime
            currt = datetime.datetime.now()
            currts = "%04d%02d%02d%02d%02d%02d" % (currt.year, currt.month, currt.day, currt.hour, currt.minute, currt.second)

            return render_to_response('stock_formula.html')                
        except Exception, ex:
            print str(ex)
            return HttpResponse("")

def test9(request):
    return render_to_response('stock_indice.html')

@csrf_exempt
def test10(request):
     if request.method == 'POST':
        #url = request.get_full_path()
        sdate = request.POST.get('sdate', '20110201')
        edate = request.POST.get('edate', '20991231')
        
        s = request.POST['iscript']
        s = s.replace('\r', '')
        s = urllib.unquote(s)
        s = s.split('\n')

        #import cx_Oracle
        #from scriptt import DATAITEM
        #connection = cx_Oracle.connect('istock_user', 'istock_user', 'localhost:1521/istock')
        cursor = connection.cursor()
        sql = "select OPEN, HIGH, LOW, CLOSE, VOLUMN, ADJCLOSE, DATETIME, STOCK_ID from STOCK_DAYLINE_INFO where " +"DATETIME>='"+str(sdate)+"' and DATETIME <= '" +str(edate)+"' order by STOCK_ID,DATETIME"        
        cursor.execute(sql)
        rows = cursor.fetchall()
        """
        openlist=[]
        highlist=[]
        lowlist=[]
        closelist=[]
        volumn=[]
        adjclose=[]
        for i in range(0, len(rows)):
                date = int(rows[i][6])
                openlist.append(DATAITEM(float(rows[i][0]), date))
                highlist.append(DATAITEM(float(rows[i][1]), date))
                lowlist.append(DATAITEM(float(rows[i][2]), date))
                closelist.append(DATAITEM(float(rows[i][3]), date))
                volumn.append(DATAITEM(float(rows[i][4]), date))
                adjclose.append(DATAITEM(float(rows[i][5]), date))
        """
        i = 0
        table_data = {}
        while i < len(rows):
            curr_stock = str(rows[i][7])
            table_data[curr_stock] = []
            j = i
            while j < len(rows) and str(rows[j][7]) == curr_stock:
                table_data[curr_stock].append(rows[j])
                j = j+1
            
            i = j
        #print table_data['600000']
        print len(rows)
        satisfy_stock = []

        c = None
        
        for i in table_data.keys():
            openlist=[]
            highlist=[]
            lowlist=[]
            closelist=[]
            volumn=[]
            adjclose=[]
            stockid = None
            for j in range(0, len(table_data[i])):
                date = int(table_data[i][j][6])
                stockid = str(table_data[i][j][7])
                openlist.append(DATAITEM(float(table_data[i][j][0]), date))
                highlist.append(DATAITEM(float(table_data[i][j][1]), date))
                lowlist.append(DATAITEM(float(table_data[i][j][2]), date))
                closelist.append(DATAITEM(float(table_data[i][j][3]), date))
                volumn.append(DATAITEM(float(table_data[i][j][4]), date))
                adjclose.append(DATAITEM(float(table_data[i][j][5]), date))

            if c == None:            
                c=scriptt.ScriptEngine(stockid=stockid, startdate=str(sdate), enddate=str(edate),
                                       openlist=openlist, highlist=highlist, lowlist=lowlist, closelist=closelist,
                                       volumn=volumn, adjclose=adjclose)
            else:
                c.stockid = stockid
                c.openlist = openlist
                c.highlist = highlist
                c.lowlist = lowlist
                c.closelist = closelist
                c.volumn = volumn
                c.adjclose = adjclose

            #print s            
            for k in s:
                #print k
                c.parse(k)
            flag = 1
            for k in c.names.keys():
                
                if c.names[k]:
                    if c.names[k].isvector:
                        if not c.names[k].data:
                            flag = 0
                            break
                    else:
                        if not c.names[k].v:
                            flag = 0
                            break

            if flag:
                satisfy_stock.append(stockid)
                #print c.names
                        
        return HttpResponse(str(satisfy_stock))
        #print s
